local jwt = require "resty.jwt"
local cjson = require "cjson"
-- local u = require("resty.uuid")
--your secret
local secret = "5pil6aOO5YaN576O5Lmf5q+U5LiN5LiK5bCP6ZuF55qE56yR"

local M = {}

function M.auth()
    -- require Authorization request header
    local auth_header = ngx.var.http_Authorization

    if auth_header == nil then
        ngx.log(ngx.WARN, "No Authorization header")
        --ngx.say("No Authorization header")
        ngx.exit(ngx.HTTP_UNAUTHORIZED)
    end

    --ngx.say("Authorization: " .. auth_header)

    -- require Bearer token
    --local _, _, token = string.find(auth_header, "Bearer%s+(.+)")
    local token = auth_header

    if token == nil then
        --ngx.say("Missing token")
        ngx.exit(ngx.HTTP_UNAUTHORIZED)
    end

    --ngx.say("Token: " .. token)
    local jwt_obj = jwt:verify(secret, token)
    if jwt_obj.verified == false then
        --ngx.log(ngx.WARN, "Invalid token: ".. jwt_obj.reason)
        --ngx.say("Invalid token: ".. jwt_obj.reason)
        ngx.exit(ngx.HTTP_UNAUTHORIZED)
    end

    --ngx.say("JWT: " .. cjson.encode(jwt_obj))

    -- write the uid variable
    ngx.var.uid = jwt_obj.payload.foo
    -- ngx.var.uuid = u.uuid(64)
end

M.auth()

--return M